using System.Collections.Generic;
using UnityEngine;
using Verse;
using RimWorld;
using Verse.Sound;
using UnityEngine.AI;
using System;
using System.Linq;

namespace RimZombieGirl
{
    public static class Utils
    { 
        /// <summary>
        /// 在影响区域内获取所有Pawn, 并且对其执行action
        /// </summary>
        /// <param name="map">所在地图</param>
        /// <param name="center">中心格</param>
        /// <param name="radius">范围</param>
        /// <param name="action">对Pawn的操作</param>
        /// <returns></returns>
        public static int ApplyPawnInAffectedArea(Map map, IntVec3 center, float radius, System.Action<Pawn> action)
        {
            var count = 0;
            GenRadial.RadialCellsAround(center, radius, true)
                .Where(cell => cell.InBounds(map)) // 检查 cell 是否在地图边界内
                .SelectMany(cell => cell.GetThingList(map).OfType<Pawn>())
                .All(pawn =>
                {
                    try
                    {
                        action(pawn);
                        count++;
                    }
                    catch (Exception ex)
                    {
                        Log.Error($"ApplyPawnInAffectedArea Error: {ex}");
                    }
                    return true;
                });

            return count;
        }

        /// <summary>
        /// 在影响区域内获取所有Pawn, 并且对其执行action
        /// </summary>
        /// <param name="map"></param>
        /// <param name="affectedCells"></param>
        /// <param name="action"></param>
        /// <returns>影响的Pawn数量</returns>
        public static int ApplyPawnInAffectedArea(Map map, List<IntVec3> affectedCells, System.Action<Pawn> action)
        {
            int count = 0;
            foreach (IntVec3 cell in affectedCells)
            {
                foreach (Thing thing in cell.GetThingList(map))
                {
                    if (thing is Pawn pawn)
                    {
                        try
                        {
                            action(pawn);
                        }
                        catch (Exception ex)
                        {
                            Log.Error($"ApplyPawnInAffectedArea Error: {ex}");
                        }
                        count++;
                    }
                }
            }
            return count;
        }
    }
}